package com.samnative.pineapple.main;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.samnative.pineapple.entity.ShareData;
import com.samnative.pineapple.instance.AppPrefer;
import com.samnative.pineapple.service.MainService;
import com.samnative.pineapple.utils.ImgurlDownloadUtils;
import com.samnative.pineapple.value.Config;
import com.samnative.pineapple.widget.ChooseMapPop;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.WebChromeClient;
import com.kongzue.dialog.interfaces.OnDialogButtonClickListener;
import com.kongzue.dialog.util.BaseDialog;
import com.kongzue.dialog.v3.MessageDialog;
import com.shashank.sony.fancytoastlib.FancyToast;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;

/**
 * 加载web
 */
public class Webview2Activity extends BaseActivity implements View.OnClickListener {
    private TextView tv_title;
    private String url;
    private boolean isAddToken = true;
    private LinearLayout ll_content;

    private AgentWeb mAgentWeb;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_webview2;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        url = getIntent().getStringExtra("url");
        isAddToken = getIntent().getBooleanExtra("isAddToken", true);
        find(R.id.iv_back).setOnClickListener(this);
        ll_content = find(R.id.ll_content);
        tv_title = find(R.id.tv_title);

        addTokenForUrl();

        mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(ll_content, new LinearLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .setWebChromeClient(mWebChromeClient)
                .createAgentWeb()
                .ready()
                .go(url);

        Log.e("2255",url);
    }

    /**
     * 在URL后面加上Token
     */
    private void addTokenForUrl() {
        if (!isAddToken) {
            return;
        }
        if (url.contains("?")) {
            url = url + "&mtoken=" + AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, "") + "&_v=A" + Config._API_VERSION;
        } else {
            url = url + "?mtoken=" + AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, "") + "&_v=A" + Config._API_VERSION;
        }
    }

    private WebChromeClient mWebChromeClient = new WebChromeClient() {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            tv_title.setText(title);
        }
    };


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (mAgentWeb.handleKeyEvent(keyCode, event)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mAgentWeb.getWebLifeCycle().onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mAgentWeb.getWebLifeCycle().onResume();
    }

    @Override
    public void onBackPressed() {
        if (!mAgentWeb.back()) {
            finish();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        LogUtils.e("onActivityResult, requestCode:" + requestCode
                + ",resultCode:" + resultCode);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 0:
                    break;
                default:
                    break;
            }
        }

        if (resultCode == 201) {

        }

    }

    @Override
    protected void onNewIntent(Intent intent) {
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                if (!mAgentWeb.back()) {
                    finish();
                }
                break;
        }
    }


    /**
     * h5调用安卓
     *
     * @author WangPeng
     */
    final class loadJavaScriptInterface {


        /**
         * H5直接调起分享功能
         * <p>
         * 传入分享的四个参数
         *
         * @param shareTitle   分享标题
         * @param shareContent 分享副标题
         * @param shareImage   图标地址
         * @param shareUrl     分享链接地址
         */
        @JavascriptInterface
        public void startShare(String shareTitle, String shareContent, String shareImage, String shareUrl) {
            LogUtils.e("收到H5直接调起分享功能参数:\nshareTitle=" + shareTitle + "\nshareContent=" + shareContent +
                    "\nshareImage=" + shareImage + "\nshareUrl=" + shareUrl);
            ShareData sd = new ShareData();
            sd.setTitle(shareTitle);
            sd.setDescription(shareContent);
            sd.setImage(shareImage);
            sd.setUrl(shareUrl);
            Intent intent = new Intent(mContext, ShareHelperActivity.class);
            intent.putExtra("shareData", sd);
            startActivity(intent, R.anim.act_enter_top_alpha, R.anim.act_enter_bottom_alpha);
        }

        /**
         * H5调用原生下载,点击下载按钮远程调用此方法,传入两个参数
         *
         * @param url 下载文件名称
         * @param url 下载链接
         */
        @JavascriptInterface
        public void requestDownload(String fileName, String url) {

            LogUtils.e("收到H5传入的下载参数=" + fileName + "+" + url);

            MessageDialog.show(Webview2Activity.this, null, "是否下载" + fileName + "?",
                    getString(R.string.confirm), getString(R.string.cancel)).setOnOkButtonClickListener(
                    new OnDialogButtonClickListener() {
                        @Override
                        public boolean onClick(BaseDialog baseDialog, View v) {

                            //进入本地下载流程,通知本地后台启动下载线程
                            Intent intent = new Intent(mContext, MainService.class);
                            intent.putExtra(Config.SERVICE_KEY,
                                    Config.SERVICE_DOWNLOAD_FILE);
                            intent.putExtra("downloadurl", url);
                            intent.putExtra("filename", fileName);
                            startService(intent);

                            return false;
                        }
                    });
        }

        /**
         * H5调用原生的导航
         */
        @JavascriptInterface
        public void go2Map(String lng, String lat, String address) {

            LogUtils.e("收到H5传入的地图参数=" + lng + "+" + lat + "+" + address);

            Webview2Activity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //选择导航
                    ChooseMapPop cmp = new ChooseMapPop(mContext, address, lat + "", lng + "");
                    cmp.showAtLocation(ll_content, Gravity.CENTER, 0, 0);
                }
            });


        }

        /**
         * H5保存图片到手机本地
         */
        @JavascriptInterface
        public void saveToAlbum(String str) {

            LogUtils.e("收到H5传入的图片地址=" + str);

            try {
                JSONObject jsonData = new JSONObject(str);
                String imgurl = jsonData.optString("url");
                Log.e("2255", "图片地址=" + imgurl);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String savaPath = mContext.getCacheDir().getAbsoluteFile() + Config.SaveImgPath + +System.currentTimeMillis() + ".png";
                        ImgurlDownloadUtils.GetImageInputStream(imgurl, new Handler.Callback() {
                            @Override
                            public boolean handleMessage(Message msg) {
                                if (msg.what == 200) {
                                    Webview2Activity.this.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Bitmap bitmap = (Bitmap) msg.obj;
                                            ImgurlDownloadUtils.SavaImage(bitmap, savaPath);

                                            File savedFile = new File(savaPath);
                                            if (savedFile.exists()) {
                                                FancyToast.showToast(mContext, "保存成功", FancyToast.SUCCESS, false);

                                                // 最后通知图库更新
                                                try {
                                                    MediaStore.Images.Media.insertImage(mContext.getContentResolver(),
                                                            savedFile.getAbsolutePath(), savedFile.getName(), null);
                                                    savedFile.delete();
                                                } catch (FileNotFoundException e) {
                                                    e.printStackTrace();
                                                }
                                                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                                                Uri uri = Uri.fromFile(new File(savaPath));
                                                intent.setData(uri);
                                                mContext.sendBroadcast(intent);


                                                if (!UMShareAPI.get(mContext).isInstall(Webview2Activity.this, SHARE_MEDIA.WEIXIN)) {
                                                    return;
                                                }

                                                UMImage image = new UMImage(Webview2Activity.this, imgurl);//网络图片
                                                new ShareAction(Webview2Activity.this).setPlatform(SHARE_MEDIA.WEIXIN).withMedia(image).share();

                                            }
                                        }
                                    });
                                } else {
                                    FancyToast.showToast(mContext, "保存失败", FancyToast.WARNING, false);
                                }

                                return false;
                            }
                        });


                    }
                }).start();

            } catch (JSONException e) {
                e.printStackTrace();
            }


        }

        /**
         * 打开微信小程序(敏付小程序支付)
         */
        @JavascriptInterface
        public void payMiniProgram(String appid, String spath) {
            LogUtils.e("收到H5跳转微信小程序参数=" + appid + "+" + spath);
            IWXAPI api = WXAPIFactory.createWXAPI(mContext, Config.wechatId);//appID
            final WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
            req.userName = appid;
            req.path = spath;
            api.sendReq(req);
        }

        /**
         * 打开登录页面
         */
        @JavascriptInterface
        public void gotoAppLogin() {
            Intent intent = new Intent(mContext, LoginActivity.class);
            intent.putExtra("webinto", true);
            startActivityForResult(intent, 201);
        }

        /**
         * 隐藏标题栏
         */
        @JavascriptInterface
        public void hideTitleBar() {


        }

        /**
         * 退出页面
         */
        @JavascriptInterface
        public void exitActivity() {
            finish();
        }
    }

}
